package com.aco.fatureapp.utilitary;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

public class BitmapUtil {

	public static void compress(final String caminho) throws IOException {
		FileOutputStream fileOutputStream = null;
		Bitmap myImage = null;

		final File imgFile = new File(caminho);

		if (imgFile.exists()) {
			myImage = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
		}

		if (myImage != null) {
			fileOutputStream = new FileOutputStream(imgFile);

			final BufferedOutputStream bos = new BufferedOutputStream(
					fileOutputStream);

			myImage.compress(CompressFormat.JPEG, 50, bos);

			bos.flush();
			bos.close();

			fileOutputStream.flush();
			fileOutputStream.close();
		}
	}

	public static Bitmap loadBitmap(final String caminho) {
		Bitmap foto = null;

		final File imgFile = new File(caminho);

		if (imgFile.exists()) {
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;

			BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);

			options.inSampleSize = calcInSampleSize(options, 600, 440);
			options.inJustDecodeBounds = false;

			foto = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
		}

		return foto;
	}

	private static int calcInSampleSize(final BitmapFactory.Options options,
			final int reqWidth, final int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			final int halfHeight = height / 2;
			final int halfWidth = width / 2;

			while ((halfHeight / inSampleSize) > reqHeight
					&& (halfWidth / inSampleSize) > reqWidth) {
				inSampleSize *= 2;
			}
		}

		return inSampleSize;
	}

	public static Bitmap scaleBitmap(Bitmap bm, float scalingFactor) {
		int scaleHeight = (int) (bm.getHeight() * scalingFactor);
		int scaleWidth = (int) (bm.getWidth() * scalingFactor);

		return Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
	}
}
